package com.easymin.weixin.common;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by shine on 15/8/26.
 */

public class IpHelper {

    /**
     * 获取IP地址.
     */

    public static String getIp(HttpServletRequest request) {

        String ip = request.getHeader("X-Forwarded-For");
        System.out.println("X-Forwarded-For");

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {

            ip = request.getHeader("X-Real-IP");
            System.out.println("X-Real-IP");

            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                return request.getRemoteAddr();
            } else {
                // 多次反向代理后会有多个IP值，第一个为真实IP。
                int index = ip.indexOf(',');

                if (index != -1) {
                    return ip.substring(0, index);
                } else {
                    return ip;
                }
            }

        }

        return ip;
    }

}
